package com.zbc.aop;

import com.zbc.annotations.AuthCheck;
import com.zbc.domain.entity.User;
import com.zbc.enums.ErrorCode;
import com.zbc.enums.UserRoleEnum;
import com.zbc.exception.BusinessException;
import com.zbc.service.UserService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验 AOP
 * @author fangyu
 * @version v1.0.0
 * @since 2025/9/2 00:43
 */
@Component
@Aspect
@RequiredArgsConstructor
public class AuthInterceptor {
    private final UserService userService;

    /**
     * 权限校验 AOP
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     * @return Object
     * @throws Throwable 抛出异常
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 1. 获取到 HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        // 2. 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 3. 获取注解权限的枚举
        String requiredRole = authCheck.requiredRole();
        UserRoleEnum requiredRoleEnum = UserRoleEnum.getEnumByValue(requiredRole);
        // 4. 说明不需要权限也能访问(接口不需要进行权限校验), 放行
        if (requiredRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 5. 获取当前登录用户的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 6. 没有权限, 拦截
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 7. 需要管理员权限, 但当前用户不是管理员, 拦截
        if (UserRoleEnum.ADMIN.equals(requiredRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 8. 通过权限校验, 放行
        return joinPoint.proceed();
    }
}